package servlet.admin;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;

@WebServlet("/adminaddbook")
@MultipartConfig
public class AddBook extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");

        // 读取前端发送的文本数据
        String bookName = null;
        String categoryID = null;
        String author = null;
        String description = null;
        String publisher = null;
        double price = 0.0;

        // 获取文件部分
        Part filePart = request.getPart("image");
        InputStream fileContent = filePart.getInputStream();
        // 获取文件名
        String fileName = getSubmittedFileName(filePart);

        // 在控制台输出接收到的数据
        System.out.println("图像文件名: " + fileName);

        // 获取其他表单字段
        for (Part part : request.getParts()) {
            String fieldName = part.getName();
            if (fieldName.equals("bookName")) {
                bookName = readFormField(part);
            } else if (fieldName.equals("categoryID")) {
                categoryID = readFormField(part);
            } else if (fieldName.equals("author")) {
                author = readFormField(part);
            } else if (fieldName.equals("description")) {
                description = readFormField(part);
            } else if (fieldName.equals("publisher")) {
                publisher = readFormField(part);
            } else if (fieldName.equals("price")) {
                price = Double.parseDouble(readFormField(part));
            }
        }

        // 在控制台输出接收到的文本数据
        System.out.println("图书名称: " + bookName);
        System.out.println("分类ID: " + categoryID);
        System.out.println("图书作者: " + author);
        System.out.println("图书简介: " + description);
        System.out.println("出版社: " + publisher);
        System.out.println("价格: " + price);

        // 保存图像文件到服务器
        saveFileToServer(fileContent, fileName);
        // 响应给前端
        PrintWriter out = response.getWriter();
        out.println("接收到图书信息");
    }

    private String getSubmittedFileName(Part part) {
        String header = part.getHeader("content-disposition");
        for (String headerPart : header.split(";")) {
            if (headerPart.trim().startsWith("filename")) {
                return headerPart.substring(headerPart.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }

    private String readFormField(Part part) throws IOException {
        // 使用输入流读取表单字段数据
        InputStream inputStream = part.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    }

    private void saveFileToServer(InputStream fileContent, String fileName) throws IOException {
        // 定义文件保存路径
        String savePath = "D:\\CodeAll\\BookStore\\BookStoreOnline\\BookStoreOnline\\src\\main\\webapp\\img\\book\\" + fileName;

        // 保存文件到指定路径
        try (OutputStream out = new FileOutputStream(new File(savePath))) {
            int read;
            byte[] bytes = new byte[1024];
            while ((read = fileContent.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
        }
    }
}